﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using doubanloginDll8;
using MimiDouban.Abstract;
using MimiDouban.Abstract.Beans;
using MimiDouban.Extention;

namespace MimiDouban.SongProvider
{
    /// <summary>
    /// SongProvider实现类
    /// </summary>
    class DoubanSongProvider : ISongProvider
    {
        /// <summary>
        /// 豆瓣协议类
        /// </summary>
        private DoubanProtocol doubanPrtcl = new DoubanProtocol();

        /// <summary>
        /// 当前播放列表
        /// </summary>
        private DoubanPlayList currentSongList;

        /// <summary>
        /// 播放历史列表
        /// </summary>
        private DoubanPlayedList playedlist;

        /// <summary>
        /// 当前歌曲在播放列表中的索引
        /// </summary>
        private int currentSongIndex;

        /// <summary>
        /// 当前的频道
        /// </summary>
        private int currentChannel;

        /// <summary>
        /// 是否已经登录
        /// </summary>
        private bool isLoggedIn = false;

        /// <summary>
        /// 从启动以来，登录状态是否从网络上检查过
        /// </summary>
        private bool loginStatusChecked = false;

        private string currentUser = "";

        #region ISongProvider Members

        public bool isLogin()
        {
            if (!loginStatusChecked)
            {
                string username = this.doubanPrtcl.checkLogin();
                if (username == null)
                {
                    this.isLoggedIn = false;
                }
                else
                {
                    this.isLoggedIn = true;
                    this.currentUser = username;
                }
                this.loginStatusChecked = true;
            }
            return isLoggedIn;
        }

        public DoubanUser login(string username, string password)
        {
            DoubanUser res = doubanPrtcl.login(username, password);
            if (res != null)
            {
                isLoggedIn = true;
            }

            return res;
        }

        public void onInit(out DoubanSong firstSong, out int firstChannelId,out string username)
        {
            //暂时认为默认的频道为0，即私人频道
            string strCurrentChannel = DataStore.getInstance().getString("currentChannel");
            int initChannel = 0;
            if (strCurrentChannel != null)
            {
                try
                {
                    initChannel = Int32.Parse(strCurrentChannel);
                }
                catch { }
            }

            if (isLogin())//如果当前已经登录了
            {
                username = this.currentUser;
            }
            else
            {
                username = null;
            }

            if (initChannel == 0 && !isLogin())//如果默认频道号是0，但没有登录，就设置成1（华语频道）
            {
                initChannel = 1;
            }

            currentChannel = initChannel;

            currentSongList = doubanPrtcl.getInitPlayList(initChannel);
            currentSongIndex = 0;
            playedlist = new DoubanPlayedList();

            firstSong = currentSongList.Songs[currentSongIndex];
            firstChannelId = initChannel;
        }

        public bool onLike()
        {
            doubanPrtcl.like(currentSongList.Songs[currentSongIndex].Sid, currentChannel, playedlist);
            return true;
        }

        public bool onLikeCancelled()
        {
            doubanPrtcl.likeCancle(currentSongList.Songs[currentSongIndex].Sid, currentChannel, playedlist);
            return true;
        }

        public DoubanSong onDislike()
        {
            currentSongList = doubanPrtcl.disLike(currentSongList.Songs[currentSongIndex].Sid, currentChannel, playedlist);
            currentSongIndex = 0;

            return currentSongList.Songs[currentSongIndex];
        }

        public DoubanSong onNext()
        {
            string sid = currentSongList.Songs[currentSongIndex].Sid;
            playedlist.add(new DoubanPlayedSong(sid, "s"));

            do
            {
                currentSongList = doubanPrtcl.nextSong(sid, currentChannel, playedlist);
                currentSongIndex = 0;
            } while (currentSongList.Songs.Count == 0);

            return currentSongList.Songs[currentSongIndex];
        }

        public DoubanSong onChannelChanged(int channelId)
        {
            currentSongIndex = 0;
            do
            {
                currentSongList = doubanPrtcl.changeChannel(channelId);
            } while (currentSongList.Songs.Count == 0);
            currentChannel = channelId;
            playedlist.PlayedSongs.Clear();
            return currentSongList.Songs[currentSongIndex];
        }

        public DoubanSong onFinished()
        {
            for (int i = 0; i < 12; i++ )
            {
                try
                {
                    //当前播放的不是最后一首
                    if (currentSongIndex < currentSongList.Songs.Count - 1)
                    {
                        doubanPrtcl.songFinished(currentSongList.Songs[currentSongIndex].Sid, currentChannel);
                        playedlist.add(new DoubanPlayedSong(currentSongList.Songs[currentSongIndex].Sid, "p"));
                        currentSongIndex++;
                    }
                    //当所有的歌曲都已经播放完了
                    else
                    {
                        playedlist.add(new DoubanPlayedSong(currentSongList.Songs[currentSongIndex].Sid, "p"));
                        currentSongList = doubanPrtcl.songFinished(currentSongList.Songs[currentSongIndex].Sid, currentChannel, playedlist);
                        currentSongIndex = 0;
                        MimiDouban.Test.TestLog.getInstance().info("all played:" + currentSongList.Songs.Count);
                    }
                    if ( currentSongList.Songs[currentSongIndex]!=null )
                    {

                        if ( i >= 0 )
                        {
                        	MimiDouban.Test.TestLog.getInstance().info("DoubanSongProvider OnFinished :" + i + ",title:" + currentSongList.Songs[currentSongIndex].Title + ",list count:" + currentSongList.Songs.Count + ",cur:" + currentSongIndex + ",try:" + i);
                        }
                        break;
                    }
                }
                catch (System.Exception ex)
                {
                    MimiDouban.Test.TestLog.getInstance().error("DoubanSongProvider OnFinished catch 尝试：" + i, ex);
                    if (i == 12)
                    {
                        return null;
                    }
                }
                System.Threading.Thread.Sleep(50);
            }



            return currentSongList.Songs[currentSongIndex];
        }

        public void end()
        {
            //记录当前用户播放的频道
            DataStore.getInstance().saveString("currentChannel", this.currentChannel.ToString());
            this.doubanPrtcl.end();
        }
        #endregion
    }
}
